package com.changgou.user.controller;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.exceptions.ClientException;
import com.changgou.user.pojo.User;
import com.changgou.user.service.UserService;
import com.changgou.user.util.SMSUtils;
import com.changgou.user.util.ValidateCodeUtils;
import com.github.pagehelper.PageInfo;
import entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/****
 * @Author:shenkunlin
 * @Description:
 * @Date 2019/6/14 0:18
 *****/

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TokenDecode tokenDecode;

    /***
     * 返回当前用户用户名
     * @return
     */
    @GetMapping("/username")
    public Result getUsernaem() {
        String username = tokenDecode.getUserInfo().get("username");
        return new Result(true, StatusCode.OK, "找到用户名", username);
    }

    /***
     *
     * @param username
     * @param phone
     * @param smscode
     * @param repassword
     * @return
     */
    @RequestMapping(value = "/edipasswordphone")
    public Result editPasswordPhone(String username, String phone, String smscode, String repassword) {
        //验证短信验证码是否正确
        String code_ = (String) redisTemplate.boundHashOps("code_").get(phone);
        if (smscode == null || !smscode.equalsIgnoreCase(code_)) {
            throw new RuntimeException("验证码不正确！");
        }
        userService.editPassword(username, repassword);
        return new Result(true, StatusCode.OK, "密码修改成功！");
    }

    /***
     * 登录用户修改密码
     * @param username  用户名
     * @param repassword    新密码
     * @return
     */
    @RequestMapping(value = "/editpassword")
    public Result editPassword(@RequestParam("username") String username, @RequestParam("repassword") String repassword) {
        //判断用户名是否为当前用户

        userService.editPassword(username, repassword);
        return new Result(true, StatusCode.OK, "密码修改成功！");
    }

    /***
     * 发送短信验证码
     * @param phone
     * @return
     */
    @GetMapping("/send4password/{username}/{phone}")
    public Result send4password(@PathVariable("username") String username, @PathVariable(value = "phone") String phone) {
        //获取用户信息，验证手机号码是否正确
        User user = userService.findById(username);
        if (user == null || !user.getPassword().equalsIgnoreCase(phone)) {
            throw new RuntimeException("用户未绑定该手机号！");
        }
        //生成6位数字验证码
        Integer code = ValidateCodeUtils.generateValidateCode(6);
        //把验证码存入Redis，key为手机号+验证码识别码
        redisTemplate.boundHashOps("code_").put(phone, code);
        //发送短信
        try {
            SMSUtils.sendShortMessage(phone, code.toString());
        } catch (ClientException e) {
            //验证码发送失败
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "验证码发送失败！");
        }
        return new Result(true, StatusCode.OK, "验证码发送成功！");
    }


    /***
     * 根据用户名和用户密码进行登录，在加入权限认证之后就不需要使用这个登录了
     */
    @RequestMapping(value = "/login")
    public Result login(String username, String password, HttpServletRequest request, HttpServletResponse response) {
        //查询用户信息
        User user = userService.findById(username);
        if (user != null && BCrypt.checkpw(password, user.getPassword())) {
            //登录成功颁发令牌
            //设置令牌信息
            Map<String, String> info = new HashMap<>();
            info.put("role", "USER");
            info.put("success", "SUCCESS");
            info.put("username", username);
            //生成令牌
            String token = JwtUtil.createJWT(UUID.randomUUID().toString(), JSON.toJSONString(info), null);
            //将令牌存入到cookies中返回
            Cookie cookie = new Cookie("token", token);
            cookie.setPath("/");
            cookie.setDomain("localhost");
            response.addCookie(cookie);
            return new Result(true, StatusCode.OK, "登录成功！", user);
        }
        return new Result(false, StatusCode.LOGINERROR, "账号或者密码错误！");
    }

    /***
     * User分页条件搜索实现
     * @param user
     * @param page
     * @param size
     * @return
     */
    @PostMapping(value = "/search/{page}/{size}")
    public Result<PageInfo> findPage(@RequestBody(required = false) User user, @PathVariable int page, @PathVariable int size) {
        //调用UserService实现分页条件查询User
        PageInfo<User> pageInfo = userService.findPage(user, page, size);
        return new Result(true, StatusCode.OK, "查询成功", pageInfo);
    }

    /***
     * User分页搜索实现
     * @param page:当前页
     * @param size:每页显示多少条
     * @return
     */
    @GetMapping(value = "/search/{page}/{size}")
    public Result<PageInfo> findPage(@PathVariable int page, @PathVariable int size) {
        //调用UserService实现分页查询User
        PageInfo<User> pageInfo = userService.findPage(page, size);
        return new Result<PageInfo>(true, StatusCode.OK, "查询成功", pageInfo);
    }

    /***
     * 多条件搜索品牌数据
     * @param user
     * @return
     */
    @PostMapping(value = "/search")
    public Result<List<User>> findList(@RequestBody(required = false) User user) {
        //调用UserService实现条件查询User
        List<User> list = userService.findList(user);
        return new Result<List<User>>(true, StatusCode.OK, "查询成功", list);
    }

    /***
     * 根据ID删除品牌数据
     * @param id
     * @return
     */
    @DeleteMapping(value = "/{id}")
    public Result delete(@PathVariable String id) {
        //调用UserService实现根据主键删除
        userService.delete(id);
        return new Result(true, StatusCode.OK, "删除成功");
    }

    /***
     * 修改User数据
     * @param user
     * @param id
     * @return
     */
    @PutMapping(value = "/{id}")
    public Result update(@RequestBody User user, @PathVariable String id) {
        //设置主键值
        user.setUsername(id);
        //调用UserService实现修改User
        userService.update(user);
        return new Result(true, StatusCode.OK, "修改成功");
    }

    /***
     * 新增User数据
     * @param user
     * @return
     */
    @PostMapping
    public Result add(@RequestBody User user) {
        //调用UserService实现添加User
        userService.add(user);
        return new Result(true, StatusCode.OK, "添加成功");
    }

    /***
     * 根据ID查询User数据
     * @param id
     * @return
     */
    //@PreAuthorize("hasAnyAuthority('user')")
    @GetMapping({"/{id}", "/load/{id}"})
    public Result<User> findById(@PathVariable String id) {
        //调用UserService实现根据主键查询User
        User user = userService.findById(id);
        return new Result<User>(true, StatusCode.OK, "查询成功", user);
    }

    /***
     * 查询User全部数据
     * @return
     */
    @GetMapping
    public Result<List<User>> findAll() {
        //调用UserService实现查询所有User
        List<User> list = userService.findAll();
        return new Result<List<User>>(true, StatusCode.OK, "查询成功", list);
    }

    /****
     * 增加用户积分
     * @param username
     * @param points
     * @return
     */
    @GetMapping(value = "/points/add")
    public Result addPoints(String username, Integer points) {
        userService.addPoints(username, points);
        return new Result(true, StatusCode.OK, "添加积分成功！");
    }
}
